package cn.edu.lingnan.controller;

import cn.edu.lingnan.domain.Dto.*;
import cn.edu.lingnan.domain.Vo.JoinProjectVo;
import cn.edu.lingnan.domain.Vo.ProjectVo;
import cn.edu.lingnan.domain.Vo.StatisticsVo;
import cn.edu.lingnan.domain.pojo.PageBean;
import cn.edu.lingnan.domain.pojo.Project;
import cn.edu.lingnan.service.ProjectService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/project")
@RequiredArgsConstructor
@Slf4j
public class ProjectController {

     private final ProjectService projectService;

    private final RedisTemplate redisTemplate;

    @PostMapping("/list")
    public Result<PageBean> list(@RequestBody ProjectDto projectDto) {
        // 构建 Redis Key，包含条件和分页信息
        String key = buildCacheKey(projectDto);

        // 从 Redis 获取数据
        PageBean pageResult = (PageBean) redisTemplate.opsForValue().get(key);
        if (pageResult != null) {
            log.info("从 Redis 中获取数据，Key: {}", key);
            return Result.success(pageResult);
        }

        log.info("从数据库查询，查询条件: {}", projectDto);
        // 从数据库查询
        pageResult = projectService.list(projectDto);

        // 存入 Redis，并设置过期时间
//        redisTemplate.opsForValue().set(key, pageResult, 10, TimeUnit.MINUTES);
        log.info("数据存入 Redis，Key: {}", key);

        return Result.success(pageResult);
    }

    // 构建缓存 Key 方法
    private String buildCacheKey(ProjectDto projectDto) {
        StringBuilder keyBuilder = new StringBuilder("projectList_");
        keyBuilder.append("pageNum:").append(projectDto.getPageNum()).append("_");
        keyBuilder.append("pageSize:").append(projectDto.getPageSize());

        if (projectDto.getUserName() != null && !projectDto.getUserName().isEmpty()) {
            keyBuilder.append("_userName:").append(projectDto.getUserName());
        }
        if (projectDto.getTeacherName() != null && !projectDto.getTeacherName().isEmpty()) {
            keyBuilder.append("_teacherName:").append(projectDto.getTeacherName());
        }
        if (projectDto.getProjectName() != null && !projectDto.getProjectName().isEmpty()) {
            keyBuilder.append("_projectName:").append(projectDto.getProjectName());
        }

        return keyBuilder.toString();
    }


    //根据id查询项目
    @GetMapping("/findById")
    public Result<ProjectVo> findById(@RequestParam("project_id") Integer id){
        log.info("id:{}", id);
        ProjectVo projectVo= projectService.findById(id);
        log.info("projectVo:{}", projectVo);
        return  Result.success(projectVo);
    }

    //删除项目成员
    @DeleteMapping("/deleteMember")
    public Result deleteMember(@RequestParam("project_id") Integer  projectId, @RequestParam("user_id") Integer userId){
        log.info("id:{},userId:{}",  projectId, userId);
        projectService.deleteMember( projectId, userId);
        return Result.success();
    }

    //添加项目成员
    @PutMapping("/addMember")
    public Result addMember(@RequestParam("project_id") Integer  projectId, @RequestParam("user_id") Integer userId){
        log.info(" 添加项目成员 project_id:{},userId:{}",  projectId, userId);
        Integer result = projectService.addMember(projectId, userId);
        if (result == 0){
            return Result.error("该学生已存在于项目成员中");
        }
        if (result == -1){
            return Result.error("该项目已停止，无法添加成员");
        }
        return Result.success("添加成功");
    }

    //停止项目/恢复项目
    @PutMapping("/updateProjectStatus")
    public Result stopProject(@RequestParam("project_id") Integer  projectId, @RequestParam("status") Integer status){
        log.info("停止项目 project_id:{},status:{}",  projectId, status);
        projectService.stopProject(projectId, status);
        return Result.success("项目已停止");
    }

    //删除项目
    @DeleteMapping("/deleteProject")
    public Result deleteProject(@RequestParam("project_id") Integer  projectId,
                                 @RequestParam("user_id") Integer userId,
                                @RequestParam("pass_word") String password){
        log.info("删除项目 project_id:{},password:{}",  projectId, password);
      Integer result =  projectService.deleteProject(projectId,userId, password);
       //删除redis缓存
        String key = "projectList_*";
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);

        if (result == 0){
            return Result.error("密码错误");
        }
        return Result.success("项目已删除");

    }
    //修改项目信息
    @PostMapping("/updateProject")
    public Result updateProject(@RequestBody UpdateProjectDto updateProjectDto){
        log.info("updateProjectDto:{}", updateProjectDto);
        projectService.updateProject(updateProjectDto);
        //删除redis缓存
        String key = "projectList_*";
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
         return Result.success("项目信息修改成功");

    }

    //添加项目
    @PostMapping("/addProject")
    public Result addProject(@RequestBody AddProjectDto addProjectDto){
        log.info("addProjectDto:{}", addProjectDto);
        projectService.addProject(addProjectDto);
        //删除redis缓存
        String key = "projectList_*";
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);

        return Result.success();
    }


    //导出为Excel
    @GetMapping("/exportExcel")
    public Result<String> exportExcel( @RequestParam("user_name") String  userName,  HttpServletResponse response) throws IOException {
        // 调用 Service 层处理 Excel 导出逻辑
        log.info("userName:{}", userName);

        projectService.exportExcel(userName,response);

        return Result.success("导出成功");
    }

    //学生加入项目
    @PutMapping("/joinProject")
    public Result joinProject(@RequestParam("project_id") Integer  projectId, @RequestParam("user_id") Integer userId){
        log.info("加入项目 project_id:{},userId:{}",  projectId, userId);
        Integer result = projectService.joinProject(projectId, userId);
        if (result == 0){
            return Result.error("该学生已加入该项目或审核中");
        }
        if (result == -1){
            return Result.error("该项目已停止，无法加入");
        }
        return Result.success("加入成功");
    }

    //查询审申请加入项目
    @GetMapping("/listJoinProject")
    public Result<List< JoinProjectVo >> listJoinProject(){
        log.info("查询审申请加入项目");
        List<JoinProjectVo> projectVos = projectService.listJoinProject();
        return Result.success(projectVos);

    }
    //同意审批加入项目
    @PutMapping("/agreeJoinProject")
    public Result agreeJoinProject(@RequestParam("project_id") Integer  projectId, @RequestParam("user_id") Integer userId){
        log.info("同意审批加入项目 project_id:{},userId:{}",  projectId, userId);
        projectService.agreeJoinProject(projectId, userId);
        return Result.success("审批成功");
    }


    //拒绝审批加入项目
    @PostMapping("/refuseJoinProject")
    public Result refuseJoinProject(@RequestBody RejectJoin RejectJoin){
        log.info("拒绝审批加入项目 RejectJoin:{}",  RejectJoin);
        projectService.refuseJoinProject(RejectJoin);
        return Result.success("审批成功");
    }

    //查询我申请加入的项目
    @GetMapping("/listMyJoinProject")
    public Result<List< JoinProjectVo >> listMyJoinProject(@RequestParam("user_id") Integer userId, @RequestParam("status") Integer status){
        log.info("查询我申请加入（审核中）的项目 userId:{}",  userId);
        List<JoinProjectVo> projectVos = projectService.listMyJoinProject(userId, status);
        return Result.success(projectVos);
    }

    //取消申请加入
    @DeleteMapping("/cancelApply")
    public Result cancelApply(@RequestParam("user_id") Integer userId, @RequestParam("project_id") Integer ProjectId) {
        log.info("cancelApply={}", userId);
         projectService.cancelApply(userId, ProjectId);
        return Result.success("取消申请成功");
    }

    //查询我创建的项目(审核中和已完成)
    @GetMapping("/listMyProject")
    public Result<List<Project>> listMyProject(@RequestParam("user_id") Integer userId,
                                               @RequestParam("status") Integer  status,
                                                @RequestParam("type") Integer   type){
        log.info("查询我创建的项目 userId:{}",  userId);
        List< Project > projectVos = projectService.listMyProject(userId, status, type);
        return Result.success(projectVos);
    }

    //取消创建项目申请
    @DeleteMapping("/cancelCreateProject")
    public Result cancelProject( @RequestParam("project_id") Integer ProjectId) {
        log.info("cancelProject={}", ProjectId);
         projectService.cancelProject(ProjectId);
        return Result.success("取消申请成功");
    }

    //管理查看需要审核的项目
    @GetMapping("/listNeedCheckProject")
    public Result<List<Project>> listNeedCheckProject(){
        log.info("查询需要审核的项目");
        List<Project> projectVos = projectService.listNeedCheckProject();
        return Result.success(projectVos);
    }

    //同意项目申请或者拒绝项目申请
    @PostMapping("/checkProject")
    public Result checkProject(@RequestBody RejectOrAgreeCreate rejectOrAgreeCreate){
        log.info("checkProject={}", rejectOrAgreeCreate);
        projectService.checkProject(rejectOrAgreeCreate);
        return Result.success("操作成功");
    }

    //统计
    @GetMapping("/statistics")
    public Result<StatisticsVo>  statistics(){
        log.info("统计");
         StatisticsVo  statisticsVo = projectService.statistics();
        return Result.success(statisticsVo);
    }





}
